import PropTypes from 'prop-types'
import { useEffect, useRef } from 'react'
import { AiEditor } from 'aieditor'
import storage from '@/libs/storage'

const ArticleForm = (props) => {
  //定义 ref
  const divRef = useRef(null)
  const aiEditorRef = useRef(null)

  //初始化 AiEditor
  useEffect(() => {
    if (divRef.current) {
      aiEditorRef.current = new AiEditor({
        element: divRef.current,
        placeholder: '点击输入内容...',
        content: '',
        contentIsMarkdown: true,
        contentRetention: true,
        draggable: true,
        pasteAsText: false,
        editable: true,
        onBlur: (ed) => {
          props.onBlur(ed.getMarkdown())
        },
        image: {
          uploadUrl: `${import.meta.env.VITE_APP_SERVICE_URL}/api/v1/file/uploadImage`,
          uploadFormName: 'file', //上传时的文件表单名称
          uploadHeaders: {
            'Authorization': 'Bearer ' + storage.get('token')
          },
          uploader: (file, uploadUrl, headers, formName) => {
            const formData = new FormData()
            formData.append(formName, file)
            return new Promise((resolve, reject) => {
              fetch(uploadUrl, {
                method: 'post',
                headers: {
                  'Authorization': 'Bearer ' + storage.get('token')
                },
                body: formData
              }).then((resp) => resp.json())
                .then(json => {
                  json.data.src = import.meta.env.VITE_APP_SERVICE_URL + json.data.src
                  resolve(json)
                }).catch((error) => {
                  reject(error)
                }).finally(() => {
                  props.onBlur(aiEditorRef.current.getMarkdown())
                })
            })
          }
        }
      })
      return () => {
        aiEditorRef.current.destroy()
      }
    }
  }, [])

  useEffect(() => {
    aiEditorRef.current.setMarkdownContent(props.content)
  }, [aiEditorRef, props.content])

  return (
    <div ref={divRef} style={{ height: '500px' }} />
  )
}

ArticleForm.propTypes = {
  content: PropTypes.string,
  onBlur: PropTypes.func
}

export default ArticleForm